public without sharing class ExWareQueryController {

  public String paramJson {get;set;}
  public String resJson {get;private set;}
  public String eqJson {get;private set;}
  public String  saveJson {get;set;}
  public String msg  {get;set;}
  public Boolean isSuccess {get;private set;}
  public String taskId {get; set;}
  public Boolean isErr {get; private set;}

   public String companyMap {get;private set;}//公司的下拉选择框

    public String enterwayMap {get; private set;}//进入方式的下拉选择框
  
    public ExWareQueryController() {
        taskId = System.currentPageReference().getParameters().get('id');
      setNil();
    }
    public void setError(String message){
      isErr = true;
      ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,message));
    }
    public void init(){
      if(taskId == null){
        setError('页面打开错误!');
        return;
      }
      getEquips();
      getCompanyMap();
      getEnterwayMap();
    }

    public void getEquips(){
       List<ExWareQueryBean> ebList = new List<ExWareQueryBean>();
      for(TaskEquipment__c te:[select Id , SerialNo__c ,InstrumentName__c,InstrumentName__r.Name
         ,InstrumentName__r.Brand__c,InstrumentName__r.NCCode__c,InstrumentName__r.Model__c ,cgeneralbid__c,OutgoingNumber__c
         ,SubcompanyInstrumentDeliveryCost__c ,EnterWay__c,InstrumentDeliveryCost__c,OutdoorDate__c
       from  TaskEquipment__c where Standers__c =:taskId]){
        ebList.add(new ExWareQueryBean(te));
      }
      eqJson = EncodingUtil.urlEncode(JSON.serialize(ebList), 'UTF-8') ;

    }
    public void getCompanyMap(){

      companyMap  =  EncodingUtil.urlEncode(JSON.serialize(ImportObject.getPicklistValues('Contract__c','Corpcode__c',true)), 'UTF-8');
    }

     public String getSelectOpts(String objName ,String fieldName ){
      Map<String ,Object> cooMap = new Map<String ,Object> ();
      cooMap.put('valueField', 'value');
      cooMap.put('textField', 'label');
      cooMap.put('panelHeight', 'auto');
      cooMap.put('limitToList', 'true');
      List<Map<String,String>>  dList = new List<Map<String,String>>();
      Map<String,String >opts = ImportObject.getPicklistValues(objName, fieldName, true);
      for (String k : opts.keySet()) {
        Map<String ,String> dataMap = new Map<String,String>();
        dataMap.put('label',opts.get(k) );
        dataMap.put('value',k );
        dList.add(dataMap);
      }  
      cooMap.put('data', dList);   
      
      return EncodingUtil.urlEncode(JSON.serialize(cooMap), 'UTF-8');

    }
    public void getEnterwayMap(){
      enterwayMap = getSelectOpts('TaskEquipment__c','EnterWay__c');
    }
    public void save(){
      msg = '';
      List<Object> resList=(List<Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
      if(resList.size() == 0){
        msg = '保存失败,没有数据!';
        return;
      }
      List<TaskEquipment__c>   tList = new List<TaskEquipment__c>();
      for (Object res : resList) {
        
        Map<String ,Object> o = (Map<String ,Object> )res;
        Object pid = o.get('productId');
        TaskEquipment__c  te = new TaskEquipment__c();
        te.Standers__c  = taskId;
        te.InstrumentName__c = String.valueOf(pid);
        te.EnterWay__c = String.valueOf(o.get('enterway'));
        te.SubcompanyInstrumentDeliveryCost__c = getDecimalValue(o.get('cost'));
        te.InstrumentDeliveryCost__c =  getDecimalValue(o.get('groupCost'));
        te.SerialNo__c = String.valueOf(o.get('selfno'));
        te.cgeneralbid__c = String.valueOf(o.get('cgeneralbid'));
        te.OutgoingNumber__c = String.valueOf(o.get('djh'));
        try{
          System.debug(o.get('outdoordate'));

          te.OutdoorDate__c = Date.valueOf(String.valueOf(o.get('outdoordate')).trim());
        }catch(Exception e ){
          System.debug(e.getMessage());
          te.OutdoorDate__c = null;
        }
        

        if(pid == null){
          msg += o.get('invname')+ ',<br/>';
          continue;
        }

        te.InstrumentName__c = String.valueOf(pid);
        tList.add(te);

      }
      if(msg.length() > 0){
        msg += '下面产品无法在系统中匹配,请联系管理员维护! '+ msg;
        return;
      }
      SavePoint sp = Database.setSavepoint();
      try {
          List<TaskEquipment__c> deleList = [select Id from TaskEquipment__c where Standers__c =:taskId];
          if(deleList != null && deleList.size() > 0)delete deleList;
          if(tList.size() > 0) insert tList;
          msg = '保存成功!';
          isSuccess = true;
      }
      catch (Exception e) {
         Database.rollback(sp);
          msg = '保存失败!'+e.getMessage();

      }

    }
    public Map<String ,String > getFieldMap(){
      Map<String ,String > km = new Map<String ,String >();
      km.put('公司', 'g.unitcode');
      km.put('助记码', 'c.invmnecode');
      km.put('单据号', 'h.vbillcode');
      km.put('型号', 'c.invtype');
      km.put('规格', 'c.invspec');
      km.put('存货名称', 'c.invname');
      km.put('存货编码', 'c.invcode');
      km.put('开票客户', 'nvl(kb.custname,(select a.custname from bd_cubasdoc a where a.pk_cubasdoc = h.pk_defdoc7))');
      km.put('终端客户', '(select a.custname from bd_cubasdoc a where a.pk_cubasdoc = h.pk_defdoc7)');
      km.put('序列号', 'x.vserialcode');
      km.put('收发类别', 's.rdname');

      return km;

    }

    //从NC 查询出库单
    public void queryExware(){

      Map<String ,Object > condition = (Map<String ,Object> )JSON.deserializeUntyped(EncodingUtil.urlDecode(paramJson, 'UTF-8'));
      System.debug(condition);
      String wherestr = '';
      Integer i = 0;
      Map<String ,String > kM = getFieldMap();
      for (String key :  condition.keySet()) {
          
        if(String.isBlank(String.valueOf(condition.get(key))) == false ){
          wherestr += ' and ';
          if(key.indexOf('djri')>=0){
            if(key == 'djristart'){
              wherestr +='  h.dbilldate >= \''+condition.get(key)+'\' ';
            }else{
              wherestr +='  h.dbilldate <= \''+condition.get(key)+'\' ';
            }
          }else if(key == '公司'){
            wherestr += kM.get(key) +' = \''+condition.get(key)+'\' ';
          }else{
            wherestr += kM.get(key) +' like \'%'+condition.get(key)+'%\' ';
          }
          i++;
        }

      }
      wherestr += ' and rownum <=200 ';

       String url = Label.queryResposityURL;

       String sql = '{"data":" '+ getSql()+wherestr+'"}';
      System.debug(sql);
        //请求

        HttpRequest req = new HttpRequest();
        req.setBody(sql);
        req.setMethod('POST');
        req.setHeader('Content-Type','text/plain');
        req.setEndpoint(url);
        HttpResponse res = Utils.postRequest(req, 2);
      ///返回结果处理
        if (res.getStatusCode() == 200) {
          System.debug(res.getBody());
            Map<String,Object> r = null;
              //如果是测试
                if(Test.isRunningTest()){
                  Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  resBody.put('result','{\"result_msg\":\"查询成功！\",\"result\":1,\"data\":[{\"nccode\":\"111\",\"company\":\"111\",\"djh\":\"111\",\"djdate\":\"111\",\"signdate\":\"111\",\"termaccount\":\"111\",\"payaccount\":\"111\",\"xydqr\":\"111\",\"ye\":\"111\",\"psncode\":\"111\",\"psnname\":\"111\",\"prodlinecode\":\"111\",\"prodlinename\":\"111\",\"djrq\":\"111\",\"djbh\":\"111\",\"currtypename\":\"111\"}]}');
                    r =  resBody;
                }else{
                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                }
          // r = (Map<String,Object>) JSON.deserializeUntyped(res.getBody());
          if(r.get('code') == 0 || r.get('code') == '0'){
             Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
              if( rs.get('result') == 1 ){
                Set<String> nccodes = new Set<String>();
                  List<Object> datas = (List<Object>)rs.get('data');
                  for(Object ob :datas){
                    Map<String,Object> m = (Map<String,Object>) ob;
                    nccodes.add(String.valueOf(m.get('nccode')));
                  }
                 Map<String,Product__c> productMap =  ImportObject.getProudctMap(nccodes);
                 List<ExWareQueryBean> ebList = new List<ExWareQueryBean>();
                 Set<String> pks = new Set<String>();
                 Set<String> selfnos = new Set<String>();
                 for(Object ob :datas){
                    ExWareQueryBean rd = new ExWareQueryBean((Map<String,Object>)ob,productMap);
                      ebList.add(rd);
                      pks.add(rd.cgeneralbid);
                      selfnos.add(rd.selfno);
                  }
                  Set<String> exEquips  = getAlreadyEquips(pks,selfnos);

                  for (ExWareQueryBean eb :ebList ) {
                    if(exEquips.contains(eb.cgeneralbid+'-'+eb.selfno))eb.isSelected = true;

                  }
                  System.debug('==>'+ebList);
              resJson = EncodingUtil.urlEncode(JSON.serialize(ebList), 'UTF-8') ;

               }else{
                 msg = String.valueOf(rs.get('result_msg'));
               }

          //resJson = EncodingUtil.urlEncode(res.getBody(), 'UTF-8') ;
        }else{
          msg = '查询出库单数据失败 : '+String.valueOf(r.get('msg'));
           ///System.debug(res.toString());
          //resJson = EncodingUtil.urlEncode('{"result":"","code":"1","msg":"接口错误,查询失败!"}','UTF-8');
        }

      }else{
        msg = '查询出库单数据失败 : '+res.getBody();
      }
  }

  public Set<String>  getAlreadyEquips(Set<String> pks , Set<String>selfnos ){

    Set<String>  exset = new Set<String>();
    for(TaskEquipment__c te:[select Id,cgeneralbid__c ,SerialNo__c ,OutgoingNumber__c  from TaskEquipment__c where cgeneralbid__c in:pks and SerialNo__c in:selfnos ]){
        exset.add(te.cgeneralbid__c +'-'+te.SerialNo__c);
    }
    return exset;
  }
  private Decimal getDecimalValue(Object val){
        if(val == null)return null;

        String  d = String.valueOf(val);
        if(d == '')return null;
        return Decimal.valueOf(d.trim());
    }
    public void setNil(){
      paramJson = '{}';
      resJson = '';
      msg = '';
      eqJson = '';
    }

    public String getSql (){
      String sql = '';
      sql +=' select distinct h.vuserdef9 , ';///\\"是否分期销售\\"
        sql +=' h.tlastmoditime , '; ///\\"最后修改时间\\"
         sql +=' h.cgeneralhid , ';//\\"出入库单表头ID\\
         sql +=' h.dbilldate djdate, '; //\\"单据日期\\"
         sql +=' h.daccountdate signdate, ';//\\"签字日期\\"
         sql +=' d.vbilltypename , ';//\\"单据类型\\"
         sql +=' h.vbillcode djh, ';//\\"单据号\\"
         sql +=' s.rdname type, ';//\\"收发类别\\"
        sql +='    g.unitcode , ';//\\"收发类别\\"
        sql +='  g.unitshortname company, ';//\\"收发类别\\"
         sql +=' nvl(kb.custname, ';
        sql +='    (select a.custname ';
        sql +='       from bd_cubasdoc a ';
        sql +='      where a.pk_cubasdoc = h.pk_defdoc7)) payaccount, ';//\\"开票客户\\"
         sql +=' (select a.custname  ';
        sql +='   from bd_cubasdoc a  ';
        sql +='  where a.pk_cubasdoc = h.pk_defdoc7) termaccount, ';//\\"终端客户\\"
         sql +=' h.vnote , ';
         sql +=' c.invcode nccode, ';//\\"存货编码\\"
         sql +=' c.invmnecode serialno, ';//\\"助记码\\"
         sql +=' c.invname , ';//\\"存货名称\\"
         sql +=' c.invspec  spec , ';//\\"规格\\"
         sql +=' c.invtype model, ';//\\"型号\\"
         sql +=' x.vserialcode selfno, ';//\\"序列号\\"
         sql +=' \'1\' as num, ';//\\"数据量\\"
         sql +=' c.def6 swjhdj, ';//生物计划单价
        sql += ' b.cgeneralbid  , '; //出库单明细PK
         sql +=' (select p1.user_name from sm_user p1 where p1.cuserid = h.coperatorid and p1.pk_corp = \'0001\' ) createpsn, ';
         sql +='  (select p2.user_name from sm_user p2 where p2.cuserid = h.cregister and p2.pk_corp = \'0001\') signpsn ';
          sql +=' from ic_general_h H ';
        sql +=' inner join IC_GENERAL_B B ';
       sql +='  on H.CGENERALHID = B.CGENERALHID ';
      sql +=' left join ic_general_bb2 x ';
      sql +=' on b.cgeneralbid = x.coutbillbodyid ';
      sql +=' left join bd_cumandoc k ';
       sql +=' on h.ccustomerid = k.pk_cumandoc ';
      sql +=' left join bd_cubasdoc kb ';
       sql +=' on nvl(k.pk_cubasdoc, h.pk_defdoc7) = kb.pk_cubasdoc ';
      sql +=' left join bd_rdcl s ';
      sql +=' on h.cdispatcherid = s.pk_rdcl ';
    sql +=' inner join bd_corp g ';
      sql +=' on h.pk_corp = g.pk_corp ';
     sql +=' inner join ic_billtype d ';
       sql +=' on h.cbilltypecode = d.cbilltypecode ';
     sql +=' inner join bd_invbasdoc c ';
      sql +=' on b.cinvbasid = c.pk_invbasdoc ';
      sql +=' left join bd_busitype y ';
      sql +=' on h.cbiztype = y.pk_busitype ';
     sql +=' where H.DR = 0 ';
       sql +=' and b.dr = 0 ';
       sql +=' and nvl(x.dr, 0) = 0 ';
       sql +=' and nvl(y.dr, 0) = 0  ';
       sql +=' and h.fbillflag <> 2 ';
       sql +=' and (c.invcode like \'30%\' OR c.invcode like \'10%\' OR ';
      sql +='    c.invcode like \'12%\') ';
       sql +=' and ((H.cbilltypecode = \'4C\' and ';
      sql +='   (y.businame LIKE \'%仪器销售%\' or y.businame like \'%出口流程\')) ';
      sql +='   or (H.cbilltypecode = \'4D\' and s.rdname = \'资产公司转固\' and ';
       sql +='   h.pk_corp in (\'1001\', \'1006\', \'1011\', \'1016\'))  ';
      sql +='   or ';
       sql +='   (H.cbilltypecode = \'4D\' and ';
        sql +='  h.cdptid in (select pk_deptdoc ';
       sql +='                    from bd_deptdoc ';
       sql +='                   where substr(deptcode, 5, 2) = \'09\') and ';
       sql +='   h.pk_corp not in (\'1001\', \'1006\', \'1011\', \'1016\')) ';
      sql +='    or (H.cbilltypecode = \'4H\' AND s.rdname = \'借还货出库\')   ';     
      sql +='    or (H.cbilltypecode = \'4I\' AND s.rdname = \'其他出库\') OR ';
      sql +='    (H.cbilltypecode = \'4I\' AND ';
      sql +='    H.PK_CORP in (\'1001\', \'1006\', \'1011\', \'1016\') AND ';
      sql +='    s.rdname in (\'资产公司转固\', \'资产内部转固\') and ';
      sql +='    h.cdptid in (select pk_deptdoc ';
      sql +='                     from bd_deptdoc  where ';
      sql +='   substr( regexp_replace(deptcode,\'[^0-9]\'),0,2) = \'09\'))) ';

      return sql;
    }

    public class ExWareQueryBean{
      public String company;//公司
      public String djh ;//单据号
      public String djdate ;//单据日期
      public String payaccount ;//开票客户
      public String termaccount ;//终端客户
      public String nccode ;//存货编码
      public String spec ;//规格
      public String model ;//型号
      public String serialno ;//助记码(货号)
      public String type ;//收发类别
      public String  invname ;//产品名称
      public String signdate ;//签字日期
      public String productId ;//产品ID
      public String brand ;//品牌
      public String selfno;//机身号 or 序列号
      public String outdoordate;
      public String cgeneralbid ;//出库单明细PK

      public String enterway ;//进入方式
      public Decimal cost ;//投放成本
      public Decimal groupCost ;//集团成本
      public Boolean isSelected ; //sf 中是否已经被选过
      public Boolean isExistInSF; //sf中是否存在这个产品
      public ExWareQueryBean(Map<String,Object> e ,Map<String,Product__c> pMap ){
        /*company = String.valueOf(e.get('公司'));
        djh = String.valueOf(e.get('单据号'));
        djdate = String.valueOf(e.get('单据日期'));
        payaccount = String.valueOf(e.get('开票客户'));
        termaccount = String.valueOf(e.get('终端客户'));
        nccode = String.valueOf(e.get('存货编码'));
        spec = String.valueOf(e.get('规格'));
        serialno = String.valueOf(e.get('助记码'));
        model = String.valueOf(e.get('型号'));
        type = String.valueOf(e.get('收发类别'));
        invname = String.valueOf(e.get('存货名称'));
        signdate = String.valueOf(e.get('签字日期'));
        selfno = String.valueOf(e.get('序列号'));*/

        company = String.valueOf(e.get('company'));
        djh = String.valueOf(e.get('djh'));
        djdate = String.valueOf(e.get('djdate'));
        payaccount = String.valueOf(e.get('payaccount'));
        termaccount = String.valueOf(e.get('termaccount'));
        nccode = String.valueOf(e.get('nccode'));
        spec = String.valueOf(e.get('spec'));
        serialno = String.valueOf(e.get('serialno'));
        model = String.valueOf(e.get('model'));
        type = String.valueOf(e.get('type'));
        invname = String.valueOf(e.get('invname'));
        signdate = String.valueOf(e.get('signdate'));
        selfno = String.valueOf(e.get('selfno'));
        outdoordate = String.valueOf(e.get('djdate'));
        Product__c p = pMap.get(nccode) ;
        cgeneralbid = String.valueOf(e.get('cgeneralbid'));

        if(p != null){
          if(model == null) model = p.Model__c;
          productId = p.Id ;
          brand = p.Brand__c;
        }
        isExistInSF = productId != null ;
        isSelected = false;

      }
      public ExWareQueryBean( TaskEquipment__c te ){
        nccode = te.InstrumentName__r.NCCode__c;
        invname = te.InstrumentName__r.Name ;
        brand = te.InstrumentName__r.Brand__c;
        model = te.InstrumentName__r.Model__c;
        selfno = te.SerialNo__c;
        productId = te.InstrumentName__c;
        enterway = te.EnterWay__c;
        cost = te.SubcompanyInstrumentDeliveryCost__c;
        groupCost = te.InstrumentDeliveryCost__c;
        outdoordate = te.OutdoorDate__c == null ? '': Datetime.newInstance(te.OutdoorDate__c.year(), te.OutdoorDate__c.month(), te.OutdoorDate__c.day()).format('yyyy-MM-dd');
        isExistInSF = true;
        cgeneralbid = te.cgeneralbid__c;
        djh = te.OutgoingNumber__c ;  
        isSelected = false;

      }


    }

}